﻿
Public Class Verificador
    Public _RutaResp As String = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) & " \Verificador de vales\"
    Public _RutaReportes As String = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) & " \Verificador de vales\Diseños\"
    Public _RutaConexion As String = Application.StartupPath & "\vales.ini"
    Public _FechaRestauracion As String
    Dim _ValesLeidos As String = ""
    Delegate Sub DborraRespaldos()

    Private Sub BorrarRespaldos()
        Dim Files = (From F In IO.Directory.GetFiles(_RutaResp) Where DateDiff(DateInterval.Day, Now.Date, IO.File.GetCreationTime(F)) <= -15)
        For Each F In Files
            If IO.File.Exists(F) = False Then
                Continue For
            End If
            IO.File.Delete(F)
            Application.DoEvents()
        Next
        If Retaurar.InvokeRequired Then
            Dim VD As New DborraRespaldos(AddressOf BorrarRespaldos)
            Retaurar.Invoke(VD)
        Else
            Retaurar.Enabled = IIf(IO.Directory.GetFiles(_RutaResp).Length > 0, True, False)
        End If
    End Sub
    Private Sub AgregaValeLista(Info As DataRow, Optional Restaurado As Boolean = False, Optional FechaLeido As String = "01/01/1900")
        If IO.Directory.Exists(_RutaResp) = False Then
            IO.Directory.CreateDirectory(_RutaResp)
        End If
        If DSvalesVendidos.ValesEscaneados.Select("nums='" & Info("nums") & "'").Length > 0 Then
            Return
        End If
        _ValesLeidos = _ValesLeidos & "'" & Info("nums") & "',"
        Dim Nr = DSvalesVendidos.ValesEscaneados.NewRow
        For X = 0 To Info.Table.Columns.Count - 1
            Dim _Name As String = Info.Table.Columns(X).ColumnName
            Nr(_Name) = Info(_Name)
            Application.DoEvents()
        Next
        If Info("surtido") = 0 And ChDesactivarLeer.Checked = True Then
            ValesTableAdapter.UpdateSurtido(Info("nums"))
        End If
        Nr("cv") = IsDBNull(Info("fechaventa"))
        Nr("cs") = IsDBNull(Info("fechasurtido"))
        If Restaurado = False Then
            Nr("FechaLeido") = Now.Date
        Else
            If DSvalesVendidos.Leidos.Select("dato='" & Info("nums") & "' or dato ='" & Info("foliovale") & "'").Count > 0 Then
                Nr("FechaLeido") = DSvalesVendidos.Leidos.Select("dato='" & Info("nums") & "' or dato ='" & Info("foliovale") & "'")(0)("fechaleido")
            End If

        End If
        DSvalesVendidos.ValesEscaneados.Rows.Add(Nr)
    End Sub
    Private Sub GuardaVale()

        For Each R As DataRow In DSvalesVendidos.ValesEscaneados.Rows
            If ChDesactivarLeer.Checked = False Then
                ValesTableAdapter.UpdateSurtido(R("nums"))
            End If
            If R("cs") And IsDBNull(R("fechasurtido")) = False And IsDate(R("fechasurtido")) = True Then
                ValesTableAdapter.UpdateFechaSurtido(FormatDateTime(R("fechasurtido"), DateFormat.ShortDate), R("nums"))
            End If
            If R("cv") And IsDBNull(R("fechaventa")) = False And IsDate(R("fechaventa")) = True Then
                ValesTableAdapter.UpdateFechaVenta(FormatDateTime(R("fechaventa"), DateFormat.ShortDate), R("nums"))
            End If
            Application.DoEvents()
        Next
        Dim Msj As String
        Msj = IIf(ChDesactivarLeer.Checked, "Las fechas de vales leeidos se han guardado", "Todos los vales se han dado de baja")
        MsgBox(Msj, MsgBoxStyle.Information, "hecho")
        TxtVale.Focus()
    End Sub
    Private Function VerificaVale(Vale As String, Optional Restaurado As Boolean = False) As Boolean
        Dim Info
        Try
            Dim NR = DSvalesVendidos.Leidos.NewLeidosRow
            NR("DATO") = Vale
            If Restaurado = False Then
                NR("fechaleido") = Now.Date
            End If
            Dim _Vale() As String
            If Vale.IndexOf("-") = -1 Then
                If ValesTableAdapter.FillNums(DSvalesVendidos.Vales, Vale) <= 0 Then
                    Throw New Exception("El Vale no existe")
                End If
                Info = ValesTableAdapter.GetDataNums(Vale).Rows(0)
                AgregaValeLista(Info, Restaurado)
            Else
                _Vale = Split(Vale, "-")
                If _Vale.Length < 3 Then
                    Throw New Exception("El Folio " & Vale & "no es valido")
                End If
                Dim _Serie As String = _Vale(0)
                Dim _Cliente As Long = _Vale(1)
                Dim _Nums As Long = _Vale(2)
                If ValesTableAdapter.FillByfolio(DSvalesVendidos.Vales, _Serie, _Cliente, _Nums) <= 0 Then
                    Throw New Exception("El Vale no existe")
                End If
                Info = ValesTableAdapter.GetDataByfolio(_Serie, _Cliente, _Nums).Rows(0)
                AgregaValeLista(Info)
            End If
            TxtVale.Text = ""
            TxtVale.Focus()
            If DSvalesVendidos.Leidos.Select("dato='" & Info("nums") & "' or dato ='" & Info("foliovale") & "'").Length = 0 Then
                DSvalesVendidos.Leidos.Rows.Add(NR)
            End If
            If Restaurado = False Then
                DSvalesVendidos.Leidos.WriteXml(_RutaResp & "\" & Format(Now.Date, "dd-MM-yyyy") & ".xml")
            End If
            Return True
        Catch ex As Exception
            If ex.GetType.Name <> "SqlException" Then
                MsgBox(ex.Message & vbNewLine & ex.GetType.Name, MsgBoxStyle.Exclamation, "Atencion")
                TxtVale.Focus()
                DGVnoEncontrados.Rows.Add(Vale)
                TxtVale.Text = ""
            Else
                MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")
                'AsistenteConexion.ShowDialog(Me)
            End If
            Return False
        End Try
    End Function

    Private Sub Bverifica_Click(sender As Object, e As EventArgs) Handles Bverifica.Click
        If String.IsNullOrEmpty(TxtVale.Text) Then
            TxtVale.Focus()
            Exit Sub
        End If
        VerificaVale(TxtVale.Text)
    End Sub

    Private Sub TxtVale_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtVale.KeyPress
        If e.KeyChar = Chr(13) Then
            e.Handled = True
        End If
    End Sub

    Private Sub TxtVale_KeyUp(sender As Object, e As KeyEventArgs) Handles TxtVale.KeyUp
        If TxtVale.Text = "" Then
            Return
        End If
        If e.KeyCode = Keys.Enter Then
            For Each L In TxtVale.Lines
                If String.IsNullOrEmpty(L) = True Then
                    Continue For
                End If
                VerificaVale(L)
                Application.DoEvents()
            Next
        End If
    End Sub

    Private Sub Verificador_Activated(sender As Object, e As EventArgs) Handles Me.Activated
        TxtVale.Focus()
    End Sub
    Private Sub Verificador_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        If e.CloseReason = CloseReason.UserClosing Then
            e.Cancel = True
        End If
    End Sub
   
    Private Sub Verificador_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'For Each FX In IO.Directory.GetFiles(_RutaResp)
        '    MsgBox(DateDiff(DateInterval.Day, Now.Date, IO.File.GetCreationTime(FX)))
        'Next

        Dim T As New Threading.Thread(AddressOf BorrarRespaldos)
        T.IsBackground = True
        T.Start()
        'Try
        '    If IO.File.Exists(_RutaResp & "\" & Format(Now.Date, "dd-MM-yyyy") & ".xml") Then
        '        DSvalesVendidos.Leidos.ReadXml(_RutaResp & "\" & Format(Now.Date, "dd-MM-yyyy") & ".xml")
        '    End If
        'Catch
        'End Try
        Bbaja.Text = IIf(ChDesactivarLeer.Checked, "Guardar Fechas vales", "Dar de Baja Vales")

        'If IO.File.Exists(_RutaReportes & "\Microsoft.ReportViewer.ProcessingObjectModel.DLL") = False Then
        GuardarRecursoRutaApp(My.Resources.Microsoft_ReportViewer_ProcessingObjectModel, "Microsoft.ReportViewer.ProcessingObjectModel.DLL")
        'End If
        'If IO.File.Exists(_RutaReportes & "\Microsoft.ReportViewer.Common.dll") = False Then
        GuardarRecursoRutaApp(My.Resources.Microsoft_ReportViewer_Common, "Microsoft.ReportViewer.Common.dll")
        'End If
        'If IO.File.Exists(_RutaReportes & "\Microsoft.SqlServer.Types.dll") = False Then
        GuardarRecursoRutaApp(My.Resources.Microsoft_SqlServer_Types, "Microsoft.SqlServer.Types.dll")
        'End If
        'If IO.File.Exists(_RutaReportes & "\Microsoft.ReportViewer.WinForms.dll") = False Then
        GuardarRecursoRutaApp(My.Resources.Microsoft_ReportViewer_WinForms, "Microsoft.ReportViewer.WinForms.dll")
        'End If
        Dim CB As New SqlClient.SqlConnection
        cbofiltro.SelectedIndex = 2

        'Dim s = ""
        'For Each c As DataGridViewColumn In ListaVales.Columns
        '    s = s & (c.Index & " " & c.HeaderText) & vbNewLine
        'Next
        'MsgBox(s)
        If ChDesactivarLeer.Checked = True And My.Settings.AdvertenciaBajaAutomatica = False Then
            MsjDesactivaLeer.ShowDialog(Me)
        End If

        ListaVales.Columns(2).Name = "fechaventa"
        ListaVales.Columns(3).Name = "fechasurtido"
        ListaVales.Columns(4).Name = "surtido"
        ListaVales.Columns(12).Name = "EstadoVale"

        ListaVales.Columns(0).Visible = False
        ListaVales.Columns(4).Visible = False
        ListaVales.Columns(7).Visible = False
        ListaVales.Columns(9).Visible = False
        ListaVales.Columns(10).Visible = False
        ListaVales.Columns(11).Visible = False
        ListaVales.Columns(14).Visible = False
        ListaVales.Columns(15).Visible = False
        ListaVales.Columns(5).Visible = False

        ListaVales.Columns(1).DisplayIndex = 0
        ListaVales.Columns(6).DisplayIndex = 2
        ListaVales.Columns(8).DisplayIndex = 1
        ListaVales.Columns(12).DisplayIndex = 8
        ListaVales.Columns(13).DisplayIndex = 3

        ListaVales.Columns(6).HeaderText = "Denominacion"
        ListaVales.Columns(12).HeaderText = "Estado Vale"

        ListaVales.Columns(6).Width = 400
        If IO.Directory.Exists(_RutaResp) = False Then
            IO.Directory.CreateDirectory(_RutaResp)
        End If

        If IO.Directory.Exists(_RutaReportes) = False Then
            IO.Directory.CreateDirectory(_RutaReportes)
        End If

        If IO.File.Exists(_RutaConexion) = False Then
            AsistenteConexion.ShowDialog(Me)
        End If
        Dim ini As New IniFile
        If IO.File.Exists(_RutaConexion) = True Then
            ini.Load(_RutaConexion)
        Else
            MsgBox("Error Al cargar la configuracion de conexion, la aplicacion se cerrara", MsgBoxStyle.Critical, "Error")
            End
        End If
        Dim _Instancia = ini.GetKeyValue("instancia", "instancia")
        My.Settings.RunTimeSqlConnectionString = "Server=" & _Instancia & ";Database=admingas;User Id=sa;Password=admingas;Timeout=60"
        My.Settings.Save()
        Dim cn As New SqlClient.SqlConnection("Server=" & _Instancia & ";Database=admingas;User Id=sa;Password=admingas;Timeout=10")
        Try
            cn.Open()
            cn.Close()
        Catch ex As Exception
            MsgBox(ex.Message & vbCrLf & cn.ConnectionString.ToString, MsgBoxStyle.Exclamation, "Error de conexion")
            AsistenteConexion.ShowDialog(Me)
        End Try
    End Sub

    Private Sub Bbaja_Click(sender As Object, e As EventArgs) Handles Bbaja.Click
        'If ChDesactivarLeer.Checked = False Then
        If FuncionSalir("continuar") = False Then
            Return
            'End If
        End If
        GuardaVale()
        'IO.File.Delete(_RutaResp & "\v.xml")
        DSvalesVendidos.ValesEscaneados.Clear()
        'Dim R = MsgBox("¿Todo ha salido bien, desea borrar el respaldo de vales leidos?", MsgBoxStyle.YesNo, "Pregunta")
        'If R = MsgBoxResult.Yes Then
        '    IO.File.Delete(_RutaResp & "\v.xml")
        'End If
        'MsgBox("Todos los vales se han dado de baja", MsgBoxStyle.Information, "Hecho")
        TxtVale.Focus()
    End Sub

    Private Sub cbofiltro_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbofiltro.SelectedIndexChanged
        Dim _FILTRO As String = ""
        Select Case cbofiltro.Text
            Case "Activos"
                _FILTRO = "surtido=0"
            Case "Inactivos"
                _FILTRO = "surtido=1"
            Case "Sin fecha surtido"
                _FILTRO = "fechasurtido ='desconocido' or fechasurtido is null"
            Case Else
                _FILTRO = ""
        End Select
        ValesEscaneadosBindingSource.Filter = _FILTRO
    End Sub

    Private Sub BFechaVenta_Click(sender As Object, e As EventArgs) Handles BFechaVenta.Click
        If ListaVales.SelectedRows.Count = 0 Then
            MsgBox("Seleccione por lo menos un vale", MsgBoxStyle.Exclamation, "Atencion")
            Return
        End If
        For Each R As DataGridViewRow In ListaVales.SelectedRows
            If R.Cells(10).Value = False Then
                Continue For
            End If
            R.Cells(2).Value = Dfv.Value
            Application.DoEvents()
        Next
    End Sub

    Private Sub BfechaSurtido_Click(sender As Object, e As EventArgs) Handles BfechaSurtido.Click
        If ListaVales.SelectedRows.Count = 0 Then
            MsgBox("Seleccione por lo menos un vale", MsgBoxStyle.Exclamation, "Atencion")
            Return
        End If
        For Each R As DataGridViewRow In ListaVales.SelectedRows
            If R.Cells(11).Value = False Then
                Continue For
            End If
            R.Cells("fechasurtido").Value = Dfs.Value
            Application.DoEvents()
        Next
    End Sub

    Private Sub ListaVales_RowsAdded(sender As Object, e As DataGridViewRowsAddedEventArgs) Handles ListaVales.RowsAdded
        ListaVales.Columns(6).Width = 400
        Lleidos.Text = "Total leidos " & DSvalesVendidos.ValesEscaneados.Rows.Count
        Lactivos.Text = "Total activos " & DSvalesVendidos.ValesEscaneados.Select("surtido=0").Length
        Linactivos.Text = "Total inactivos " & DSvalesVendidos.ValesEscaneados.Select("surtido=1").Length
        ListaVales.ClearSelection()
        ListaVales.Rows(e.RowIndex).Cells("EstadoVale").Value = IIf(ListaVales.Rows(e.RowIndex).Cells("surtido").Value = 1, "Surtido", "Sin surtir")
        If IsDBNull(ListaVales.Rows(e.RowIndex).Cells("fechasurtido").Value) Then
            ListaVales.Rows(e.RowIndex).Cells("fechasurtido").Value = "Desconocido"
        End If
        If IsDBNull(ListaVales.Rows(e.RowIndex).Cells("fechaventa").Value) Then
            ListaVales.Rows(e.RowIndex).Cells("fechaventa").Value = "Desconocido"
        End If
        ListaVales.FirstDisplayedScrollingRowIndex = ListaVales.RowCount - 1
    End Sub

    Private Sub Retaurar_Click(sender As Object, e As EventArgs) Handles Retaurar.Click
        
        'If IO.File.Exists(_RutaResp & "\v.xml") Then
        If ListaVales.Rows.Count > 0 Then
            Dim R = MsgBox("Esto borrara los vales actuales de la lista y tendra que re escanearlos " & vbNewLine & "¿Desea continuar?", MsgBoxStyle.YesNo, "Pregunta")
            If R = MsgBoxResult.No Then
                TxtVale.Focus()
                Return
            End If
        End If
        Borrar()
        If Restauracion.ShowDialog(Me) <> Windows.Forms.DialogResult.OK Then
            Return
        End If
        For Each V As DataRow In DSvalesVendidos.Leidos.Rows
            '_ValesLeidos = _ValesLeidos & "'" & V("nums") & "',"
            VerificaVale(V("DATO"), True)
            Application.DoEvents()
        Next
        MsgBox("Restauracion de vales Respaldados, Completada", MsgBoxStyle.Information, "Atencion")
        'Else
        'MsgBox("No hay Vales Respaldados", MsgBoxStyle.Exclamation, "Atencion")
        'End If
        TxtVale.Focus()
    End Sub

    Private Sub Btodos_Click(sender As Object, e As EventArgs) Handles Btodos.Click
        ListaVales.SelectAll()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ListaVales.ClearSelection()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim sb As New System.Text.StringBuilder
        Dim Rows = (From row In ListaVales.Rows _
                Where Not DirectCast(row, DataGridViewRow).IsNewRow _
                Let RowItem = String.Join(",", Array _
                  .ConvertAll( _
                  DirectCast(row, DataGridViewRow).Cells.Cast(Of DataGridViewCell).ToArray, _
                  Function(c As DataGridViewCell) _
                    If(c.Value Is Nothing, "", c.Value.ToString))) _
                Select RowItem).ToArray

        sb = New System.Text.StringBuilder
        For Each row In Rows
            sb.AppendLine(row)
        Next
        If Len(sb.ToString) = 0 Then
            Return
        End If
        Clipboard.SetText(sb.ToString)
        sb = Nothing
        MsgBox("Vales escaneados copiados al portapapeles con exito", MsgBoxStyle.Information, "Hecho")
    End Sub
    Private Sub ReporteExcel_Click(sender As Object, e As EventArgs) Handles ReporteExcel.Click
        If _ValesLeidos.EndsWith(",") Then
            _ValesLeidos = _ValesLeidos.Substring(0, Len(_ValesLeidos) - 1)
        End If
        If Len(_ValesLeidos) <= 0 Or DSvalesVendidos.ValesEscaneados.Rows.Count = 0 Then
            MsgBox("No se han escaneado vales", MsgBoxStyle.Critical, "Error")
            TxtVale.Focus()
            Exit Sub
        End If
        ReporteadorVP.Parametros.Add(_ValesLeidos)
        ReporteadorVP.Reporte = ReporteadorVP.Reportes.Escaneados
        ReporteadorVP.ShowDialog(Me)
    End Sub

    Private Sub ReporteVales_Click(sender As Object, e As EventArgs) Handles ReporteVales.Click
        MenuReportes.MdiParent = Principal
        MenuReportes.Show()
        MenuReportes.Focus()
    End Sub
    Sub Buscar()
        Dim _Filtro As String = ""
        If TxtBuscar.Text <> "" Then
            _Filtro = "foliovale like '%" & TxtBuscar.Text & "%' or nums like '%" & TxtBuscar.Text & "%'"
            cbofiltro.SelectedIndex = 2
        End If
        ValesEscaneadosBindingSource.Filter = _Filtro
    End Sub
    Private Sub Bbuscar_Click(sender As Object, e As EventArgs) Handles Bbuscar.Click
        Buscar()
    End Sub

    Private Sub TxtBuscar_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtBuscar.KeyPress
        If e.KeyChar = Chr(13) Then
            e.Handled = True
        End If
    End Sub

    Private Sub Bbuscar_KeyUp(sender As Object, e As KeyEventArgs) Handles TxtBuscar.KeyUp
        'If e.KeyData = Keys.Enter Then
        Buscar()
        'End If
    End Sub

    Private Sub ListaVales_RowsRemoved(sender As Object, e As DataGridViewRowsRemovedEventArgs) Handles ListaVales.RowsRemoved
        Lleidos.Text = "Total leidos " & DSvalesVendidos.ValesEscaneados.Rows.Count
        Lactivos.Text = "Total activos " & DSvalesVendidos.ValesEscaneados.Select("surtido=0").Length
        Linactivos.Text = "Total inactivos " & DSvalesVendidos.ValesEscaneados.Select("surtido=1").Length
    End Sub
    Private Sub BuscarVale_Click(sender As Object, e As EventArgs) Handles BuscarVale.Click
        Form1.MdiParent = Principal
        Form1.Show()
        Form1.Focus()
    End Sub
    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        'If FuncionSalir() = True Then
        Principal.Close()
        'End If
    End Sub

    Private Sub ChDesactivarLeer_CheckedChanged(sender As Object, e As EventArgs) Handles ChDesactivarLeer.CheckedChanged
        Bbaja.Text = IIf(ChDesactivarLeer.Checked, "Guardar Fechas vales", "Dar de Baja Vales")
    End Sub
    Private Sub Borrar()
        DSvalesVendidos.InfoVale.Rows.Clear()
        DSvalesVendidos.Leidos.Rows.Clear()
        DSvalesVendidos.ValesEscaneados.Rows.Clear()
        DGVnoEncontrados.Rows.Clear()
    End Sub
    Private Sub Bborrar_Click(sender As Object, e As EventArgs) Handles Bborrar.Click
        Borrar()
    End Sub

    Private Sub ListaVales_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles ListaVales.CellContentClick

    End Sub
End Class